package com.weigj.listener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.weigj.model.CarInfo;
import com.weigj.model.ReserveHour;

/**
 * 取消预订单 
 * @author lq
 *
 */
public class CancelReserveListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		
	}

	public void contextInitialized(ServletContextEvent sce) {
		Th1 th1 = new Th1();
		th1.start();
		System.out.println(".....");
	}
	
	
	
	class Th1 extends Thread{
		public void run() {
			while(true){
				try {
					sleep(15*60*1000);
					System.out.println("取消微公交预订单开始......");
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
					Long date=new Date().getTime();
					String sql="select * from APP_RESERVEHOUR r where r.reserveState=1";
					List<ReserveHour> list=ReserveHour.dao.find(sql);
					for (int i = 0; i < list.size(); i++) {
						ReserveHour hour=list.get(i);
						try {
							Date reserveDate=sdf.parse(hour.getStr("reserveDate"));
							Long reserve=reserveDate.getTime();
							if(date>reserve){
								hour.set("reserveState", 0);
								hour.set("cancelDoc", "订单超时系统自动取消");
								hour.set("cancelDate", sdf.format(new Date()));
								hour.update();
								//更新赋值
								CarInfo car=CarInfo.dao.queryCarInfo(hour.getStr("carNum"));
								car.set("carState", "待租");
								car.update();
								Record record=new Record();
								record.set("id", "APP_CANCELRESERVE_SEQ.nextval");
								record.set("clientId",hour.get("clientId"));
								record.set("reserveId",hour.get("id"));
								record.set("cancelDate", sdf.format(new Date()));
								System.out.println(record);
								Db.save("APP_CANCELRESERVE", record);
							}
						} catch (Exception e) {
							System.out.println("出错了");
							e.printStackTrace();
						}
					}
				} catch (Exception e1) {
					System.out.println("出错了+”“");
					e1.printStackTrace();
				}
			}
		}
	}

}
